/*==============================================================
*   File Name：fd_list.c
*   Mail: a1277992967@163.com 
*   blog: http://www.ycst.club/suggest/ 
*   Author：ycst
*   Created Time：2022年08月15日 星期一 14时20分05秒
*   Describe：
*
================================================================*/

#include "../include/fd_list.h"

List *g_pList;

List* CreateList(){
	List *list = (List *)malloc(sizeof(List));
	if(list == NULL)      return NULL;
	bzero(list, sizeof(list));
	return list;
}

void DestroyList(List *pList){
	if(pList == NULL) 	return;
	free(pList);
}


int InsertList(List *pList, dev_fd tData, int iOffset){
	if(pList == NULL || iOffset == SIZE - 1 || pList->iCount >= SIZE)	return ERROR;
	int i = pList->iCount;
	if(iOffset = -1){
		pList->data[pList->iCount] = tData;
		pList->iCount++;
		return OK;
	}
	
	for(; i >= iOffset; i--){
		pList->data[i + 1] = pList->data[i];
	}
	pList->data[iOffset] = tData;
	pList->iCount++;
	return OK;
	
	
}
	

int DeleteList(List *pList, dev_fd *pData, int iOffset){
	if(pList == NULL || iOffset < 0)	return ERROR;
	int i = iOffset;
	for(; i <= pList->iCount; i++){
		pList->data[i] = pList->data[i + 1];
	}
	pList->iCount--;
	return OK;
}


int UpdateList(List *pList, dev_fd tNew, dev_fd tOld){
	if(pList == NULL)	return ERROR;
	int i = 0;
	for(; i <= pList->iCount; i++){
		if(pList->data[i].fd == tOld.fd && pList->data[i].lTime == tOld.lTime){
			pList->data[i] = tNew;
			return OK;
		}
	}
	return ERROR;
}


int SearchItem(List *pList, dev_fd tData){
	if(pList == NULL)	return ERROR;
	int i = 0;
	for(; i <= pList->iCount; i++){
		if(pList->data[i].fd == tData.fd){
			return i;
		}
	}
	return ERROR;
}

void ShowList(List *pList){
	if(pList == NULL) return;
	int i = 0;
	for(i = 0; i < pList->iCount; i++){
		printf("i = %d \t iCount = %d \t fd = %d \t Time = %ld\r\n", i, pList->iCount, pList->data[i].fd, pList->data[i].lTime);
	}
	return;
}


int DeleteTimeOutDevFromList(List *pList, fd_set *pSet, int iMax){
	if(pList == NULL || pSet == NULL)	return -1;
	int flag = 0;
	//printf("---------检测超时描述符-------------\r\n");
	for(int i = 0; i < pList->iCount; i++){
		int difftime = time(NULL) - pList->data[i].lTime;
		if(difftime > 10){
			flag = 1;
			printf("fd = %d超时 \t difftime = %d\r\n",pList->data[i].fd, difftime);
			FD_CLR(pList->data[i].fd, pSet);
			DeleteList(pList, NULL, 0);
		}
	}	
	if(flag == 1)	return SYS_UPDATE_MAX_FD;
	return SYS_OK;
}








